package com.gxp.util.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;


public class CodeFilter extends HttpServlet implements Filter {
	Logger logger = Logger.getLogger(CodeFilter.class);

	/**
	 * 
	 */
	private static final long serialVersionUID = -2941335028732367420L;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		
		logger.debug("~~~~~~~~check code~~~~~~~~");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String formCode = request.getParameter("j_code");
		String sessionCode = (String) req.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		logger.debug("session code is : " + sessionCode +  "  form code is : " + formCode);
		if (!"".equals(formCode) && formCode != null) {
			if (formCode.equalsIgnoreCase(sessionCode)) {
				filterChain.doFilter(request, response);
			} else {
				resp.sendRedirect(req.getContextPath() + "/admin?codeerror=1");
			}
		} else {
			resp.sendRedirect(req.getContextPath() + "/admin?codeerror=1");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
